package com.qf.blogsystem.controller.website;

import com.qf.blogsystem.core.controller.BaseServlet;
import com.qf.blogsystem.core.utils.BaseConstants;
import com.qf.blogsystem.entity.Comment;
import com.qf.blogsystem.entity.User;
import com.qf.blogsystem.service.CommentService;
import com.qf.blogsystem.service.impl.CommentServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@WebServlet("/CommentServlet/*")
public class CommentServlet extends BaseServlet {
    /**
     * 创建帖子业务层实现对象
     */
    private CommentService commentService = new CommentServiceImpl();

    /**
     * 添加评论信息
     * @return String
     * @throws Exception
     */
    public String add() throws Exception {
        //获取用户登录信息
        User loginUser = (User) request.getSession().getAttribute("loginUser");
        if (loginUser == null) {
            return outJson(100, "请先登录");
        }
        //获取表单数据
        Map<String, String[]> parameterMap = request.getParameterMap();
        //创建实体类
        Comment comment = new Comment();
        //把Map中的数据拷贝到实体类中
        BeanUtils.populate(comment, parameterMap);
        //入库
        comment.setUserId(loginUser.getId());
        boolean result = commentService.save(comment);
        if (result){
            //重定向当前帖子下面
            return BaseConstants.BASE_REDIRECT+":DiscussPostServlet/showDetails?id="+comment.getEntityId();
        }else {
            return outJson(100,"评论失败!");
        }
    }
}
